﻿using Crm.Infrastructure.IOC;
using Crm.Service.Instance;
using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Request.Right;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.Dto.Response.Right;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.IOC;
using CRM.Infrastructure.Tools;
using CRM.Service.EFCore;
using CRM.Service.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM.Service.Instance
{
    [Inject_]
    public class Right_Service : Base_Service, I_Right_Service
    {
        private readonly Right_IOC _right_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Org_IOC _org_IOC;

        public Right_Service(Right_IOC right_IOC, Org_IOC org_IOC, Login_IOC login_IOC)
        {
            _right_IOC = right_IOC;
            _login_IOC = login_IOC;
            _org_IOC = org_IOC;
        }
        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Rights(Right_Request_Dto dto)
        {
            
            var rights = await _right_IOC._sys_rights_EFcore.QueryAll(d =>
             (dto.isBan == -1 || d.RIsBan == dto.isBan)
             &&
             (dto.isPublish == -1 || d.RIsPublish == dto.isPublish)
             ).ToListAsync();

            //顶级
            var root =  rights.Where(d => d.RParentRid == null).OrderBy(d => d.RNo).ToList();
            //子级用递归来获取
            List<Right_Response_Dto> data = new List<Right_Response_Dto>();
            root.ForEach(d =>
            {
                data.Add(new Right_Response_Dto
                {
                    id = d.RId,
                    name = d.RName!,
                    icon = d.RIcon!,
                    explain = d.RExplain!,
                    isBan = d.RIsBan,
                    isMenu = d.RIsMenu,
                    isPublic = d.RIsPublic,
                    isPublish = d.RIsPublish,
                    time = d.RCreateTime.ToString()!,
                    url = d.RUrl!,
                    children = Get_Right_Children(d.RId, rights)
                });
            });
            return Result(1, "ok", new
            {
                data
            });
        }
        /// <summary>
        /// 获取配置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_RightConfig_Details(string id)
        {
            var rights = _right_IOC._sys_rights_EFcore.QueryAll().ToList();
            var rightsConfig = _right_IOC._sys_right_config_EFCore.QueryAll().ToList();
            var root = rights.Where(d => d.RParentRid == null).OrderBy(d => d.RNo).ToList();

            List<string> data = new List<string>();
            var right = _right_IOC._sys_rights_EFcore.QueryAll().ToList();
            var RightConfig_Details = await _right_IOC._sys_right_config_details_EFCore.QueryAll(e => e.RcdRcid == id).ToListAsync();
            foreach (var i in RightConfig_Details)
            {
                var name = right.Where(e => e.RId == i.RcdRid).SingleOrDefault()?.RName;
                data.Add(i.RcdRid);
                data.Add(name);
            }
            return Result(1, "ok", new
            {
                //配置下绑定的权限
                data,
            });
        }

        //获取所有配置

        public async Task<Api_Response_Dto> Get_RightConfig(Right_Request_Dto dto)
        {
            var depts = await _right_IOC._sys_right_config_EFCore.QueryAll(d =>
             (dto.isBan == -1 || d.RcIsBan == dto.isBan)
             ).ToListAsync();


            List<RightConfig_Response_Dto> data = new List<RightConfig_Response_Dto>();
            //获取各个职务的人数
            //var users = _sys_User_EF.QueryAll(d => d.UDeptID != null).ToList();
            depts.ForEach(d =>
            {
                var RightConfig_Details = _right_IOC._sys_right_config_details_EFCore.QueryAll(e => e.RcdRcid == d.RcId);

                data.Add(new RightConfig_Response_Dto
                {
                    id = d.RcId,
                    name = d.RcName,
                    Ctotal = RightConfig_Details.Count(),
                    CreateTime = d.RcCreateTime.ToString(),
                    Publish = d.RcIsPublish,
                });



            });

            return Result(1, "ok", new
            {
                data,
            });
        }
        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Change_Config(RightConfig_Response_Dto dto)
        {
            var data = _right_IOC._sys_right_config_EFCore.QueryAll(d => d.RcId == dto.id).SingleOrDefault();

            data.RcName = dto.name;
            _right_IOC._sys_right_config_EFCore.Update(data);
            var result = _right_IOC._sys_right_config_EFCore.SaveChanges();

            var data2 = _right_IOC._sys_right_config_details_EFCore.QueryAll().Where(d => d.RcdRcid == dto.id).ToList();
            _right_IOC._sys_right_config_details_EFCore.DeleteRange(data2);
            var result3 = _right_IOC._sys_right_config_details_EFCore.SaveChanges();

            var data3 = _right_IOC._sys_right_config_org_EFCore.QueryAll().Where(d => d.RcoRcid == dto.id).ToList();
            _right_IOC._sys_right_config_org_EFCore.DeleteRange(data3);
            var result4 = _right_IOC._sys_right_config_org_EFCore.SaveChanges();
            //职务
            foreach (var i in dto.check)
            {
                if (i != "")
                {
                    SysRightConfigOrg rights_org = new SysRightConfigOrg()
                    {
                        RcoId = Config.GUID_1(),
                        RcoRcid = dto.id,
                        RcoDeptId = null,
                        RcoIsAllDuties = 0,
                        RcoDutyId = i,
                        RcoCreateTime = DateTime.Now,
                        RcoIsPublish = 0
                    };
                    _right_IOC._sys_right_config_org_EFCore.Add(rights_org);
                }
            };

            var result5 = _right_IOC._sys_right_config_org_EFCore.SaveChanges();

            //权限
            foreach (var i in dto.configs)
            {
                if (i != "")
                {
                    SysRightConfigDetail rights = new SysRightConfigDetail()
                    {
                        RcdId = Config.GUID_1(),
                        RcdRid = i,
                        RcdRcid = dto.id,
                        RcdCreateTime = DateTime.Now,
                    };
                    _right_IOC._sys_right_config_details_EFCore.Add(rights);
                }
            };
            var result2 = _right_IOC._sys_right_config_details_EFCore.SaveChanges();


            return Result(1);
        }
        /// <summary>
        /// 获取子级权限
        /// </summary>
        /// <param name="rID"></param>
        /// <param name="rights"></param>
        /// <returns></returns>
        private IEnumerable<Right_Response_Dto> Get_Right_Children(string rID, List<SysRight> rights, string id = null)
        {
            
            var root = rights.Where(d => d.RParentRid == rID).ToList();
            var rights2 = _right_IOC._sys_user_rights_EFCore.QueryAll(d => d.UrUid == id).ToList();
            List<Right_Response_Dto> data = new List<Right_Response_Dto>();
            root.ForEach(d =>
            {
                if (id != null)
                {
                    foreach (var i in rights2)
                    {
                        if (i.UrRid == d.RId)
                        {
                            data.Add(new Right_Response_Dto
                            {
                                id = d.RId,
                                name = d.RName!,
                                icon = d.RIcon!,
                                explain = d.RExplain!,
                                isBan = d.RIsBan,
                                isMenu = d.RIsMenu,
                                isPublic = d.RIsPublic,
                                isPublish = d.RIsPublish,
                                time = d.RCreateTime.ToString()!,
                                url = d.RUrl,
                                children = Get_Right_Children(d.RId, rights)
                            });
                        }
                    }
                }
                else
                {
                    data.Add(new Right_Response_Dto
                    {
                        id = d.RId,
                        name = d.RName,
                        icon = d.RIcon,
                        explain = d.RExplain,
                        isBan = d.RIsBan,
                        isMenu = d.RIsMenu,
                        isPublic = d.RIsPublic,
                        isPublish = d.RIsPublish,
                        time = d.RCreateTime.ToString(),
                        url = d.RUrl,
                        children = Get_Right_Children(d.RId, rights)
                    });
                }

            });

            return data;
        }
    }
}
